package com.yaozheng.vocationaltraining.fragment.exam;

import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.yaozheng.vocationaltraining.R;
import com.yaozheng.vocationaltraining.activity.HomeActivity;
import com.yaozheng.vocationaltraining.adapter.PKCategoryAdapter;
import com.yaozheng.vocationaltraining.adapter.PKRoomAdapter;
import com.yaozheng.vocationaltraining.bean.CateWinRateBean;
import com.yaozheng.vocationaltraining.bean.CompareUserInfoBean;
import com.yaozheng.vocationaltraining.bean.PKCategoryBean;
import com.yaozheng.vocationaltraining.bean.PKRankBean;
import com.yaozheng.vocationaltraining.bean.PKRoomBean;
import com.yaozheng.vocationaltraining.bean.PlayerBean;
import com.yaozheng.vocationaltraining.bean.SeatBean;
import com.yaozheng.vocationaltraining.bean.UserInfoBean;
import com.yaozheng.vocationaltraining.fragment.BaseFragment;
import com.yaozheng.vocationaltraining.iview.exam.IPKHallView;
import com.yaozheng.vocationaltraining.service.exam.PKHallService;
import com.yaozheng.vocationaltraining.service.exam.PKService;
import com.yaozheng.vocationaltraining.service.impl.exam.PKHallServiceImpl;
import com.yaozheng.vocationaltraining.service.impl.exam.PKServiceImpl;
import com.yaozheng.vocationaltraining.utils.BitmapLoader;
import com.yaozheng.vocationaltraining.utils.ErrorUtils;
import com.yaozheng.vocationaltraining.utils.TypeUtils;
import com.yaozheng.vocationaltraining.view.CompareDetailDialog;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Background;
import org.androidannotations.annotations.Bean;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.UiThread;
import org.androidannotations.annotations.ViewById;

import java.lang.reflect.Array;
import java.util.ArrayList;

/**
 * Created by moon on 2017/11/15.
 */

@EFragment(R.layout.activity_pk_hall)
public class PKHallFragment extends BaseFragment implements IPKHallView {
    @ViewById
    GridView gridview;

    PKRoomAdapter pkRoomAdapter;
    ArrayList<PKRoomBean> pkRoomData = new ArrayList<>();

    @Bean(PKHallServiceImpl.class)
    PKHallService pkHallService;

    @ViewById
    TextView headTitleText;

    @ViewById
    Button quick_park_in_Button;

    public int getGameCategoryId() {
        return gameCategoryId;
    }

    public void setGameCategoryId(int gameCategoryId) {
        this.gameCategoryId = gameCategoryId;
    }

    int gameCategoryId;

    public int getPlayerLimit() {
        return playerLimit;
    }

    public void setPlayerLimit(int playerLimit) {
        this.playerLimit = playerLimit;
    }

    int playerLimit;

    public HomeActivity getHomeActivity() {
        return (HomeActivity) getActivity();
    }

    @AfterViews
    public void initView() {
        headTitleText.setText(playerLimit+"人PK大厅");
        pkHallService.init(this);


        pkRoomAdapter = new PKRoomAdapter(this,pkRoomData);
        gridview.setAdapter(pkRoomAdapter);

        gridview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {

                //pkHallService.seat();
//                getHomeActivity().openPKGameCategoryFragment(userInfo.getName(),
//                        userInfo.getAvatar(),
//                        scoreBean.getQuarter(),
//                        bean.getRate(),
//                        pkCategoryData.get(i).getId());
            }
        });
        startTiming();

    }

    public void onRefresh() {
        pkHallService.list(gameCategoryId);
    }


    @Click(R.id.quick_park_in_Button)
    public void quickPartInButtonClick() {//
        pkHallService.quickPartIn(gameCategoryId);
    }


    /**
     * 开始计时
     */
    @Background
    public void startTiming() {
        if (isResponseResult()) {
            try {
                onRefresh();
                Thread.sleep(500);
                updateTimingUI();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    @UiThread
    public void updateTimingUI() {
        startTiming();
    }

    @UiThread
    @Override
    public void responseSuccess(JSONObject jsonObject) {
        try {
            cancelLoadDataProgressDialog();
            JSONArray dataList = TypeUtils.getJsonArray(jsonObject, "data","rooms");
            if (dataList != null) {
                pkRoomData.clear();

                for (int i = 0; i < dataList.size(); i++) {
                    JSONObject jsonObject2 = dataList.getJSONObject(i);

                    PKRoomBean bean = new PKRoomBean();
                    bean.setId(jsonObject2.getInt("id"));
                    bean.setGameCateId(jsonObject2.getInt("gameCateId"));

                    ArrayList<SeatBean> seatBeans = new ArrayList<>();
                    JSONArray seatList = TypeUtils.getJsonArray(jsonObject2, "seats");
                    for (int j = 0; j < seatList.size(); j++) {
                        JSONObject seatJsonObject = seatList.getJSONObject(j);
                        SeatBean seat = new SeatBean();
                        seat.setId(seatJsonObject.getInt("id"));
                        seat.setRoomId(seatJsonObject.getInt("roomId"));
                        seat.setPlayerId(seatJsonObject.getInt("playerId"));
                        seat.setPlayerStatus(seatJsonObject.getInt("playerStatus"));
                        seat.setStartTime(seatJsonObject.getString("startTime"));

                        PlayerBean player = new PlayerBean();
                        JSONObject playerObject = seatJsonObject.getJSONObject("player");
                        player.setAvatar(TypeUtils.getJsonString(playerObject,"avatar"));
                        player.setName(TypeUtils.getJsonString(playerObject,"name"));
                        player.setWinRate(TypeUtils.getJsonInteger(playerObject,"winRate"));
                        seat.setPlayer(player);

                        seatBeans.add(seat);
                    }
                    bean.setSeats(seatBeans);

                    pkRoomData.add(bean);
                }

                pkRoomAdapter.setData(pkRoomData);
                pkRoomAdapter.notifyDataSetChanged();
            }
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
        }
    }

    @UiThread
    @Override
    public void responseError(String error) {

    }

    public void seat(int seatId,int roomId) {
        pkHallService.seat(seatId,roomId);
    }

    @UiThread
    @Override
    public void seatSuccess(JSONObject jsonObject,int roomId,int seatId) {
        if (jsonObject.getInt("error_code") == 0){
            //Toast.makeText(this.getActivity(),"座下成功"
            //        ,Toast.LENGTH_SHORT).show();
            getHomeActivity().openPKConfirmFragment(roomId,seatId,playerLimit,this);
        }else {
            Toast.makeText(this.getActivity(),jsonObject.getString("error_msg")
                    ,Toast.LENGTH_SHORT).show();
        }

    }

    @UiThread
    @Override
    public void seatError(String error) {
        Toast.makeText(this.getActivity(),error,Toast.LENGTH_SHORT).show();
    }

    @UiThread
    @Override
    public void quickPartInSuccess(JSONObject jsonObject) {
        JSONObject seatJsonObject = TypeUtils.getJsonObject(jsonObject,"data","seat");
        SeatBean seat = new SeatBean();
        seat.setId(seatJsonObject.getInt("id"));
        seat.setRoomId(seatJsonObject.getInt("roomId"));
        seat.setPlayerId(seatJsonObject.getInt("playerId"));
        seat.setPlayerStatus(seatJsonObject.getInt("playerStatus"));
        seat.setStartTime(seatJsonObject.getString("startTime"));

        getHomeActivity().openPKConfirmFragment(seat.getRoomId(),seat.getId(),playerLimit,this);
    }

    @UiThread
    @Override
    public void quickPartInError(String error) {
        Toast.makeText(this.getActivity(),error,Toast.LENGTH_SHORT).show();
    }

    @UiThread
    @Override
    public void pkCompareSuccess(JSONObject jsonObject) {
        try {
            cancelLoadDataProgressDialog();
            ArrayList<CompareUserInfoBean>  compareUserInfoBeanArrayList = new ArrayList<>();
            JSONArray dataList = TypeUtils.getJsonArray(jsonObject, "data","users");
            if (dataList != null) {

                for (int i = 0; i < dataList.size(); i++) {
                    JSONObject jsonObject2 = dataList.getJSONObject(i);

                    CompareUserInfoBean bean = new CompareUserInfoBean();
                    bean.setId(jsonObject2.getInt("id"));
                    bean.setName(jsonObject2.getString("name"));
                    bean.setUsername(jsonObject2.getString("username"));
                    bean.setAvatar(jsonObject2.getString("avatar"));
                    bean.setWinRate(TypeUtils.getJsonInteger(jsonObject2,"winRate"));
                    bean.setPosition(jsonObject2.getString("position"));
                    bean.setStoreId(jsonObject2.getInt("storeId"));
                    bean.setStoreName(jsonObject2.getString("storeName"));
                    bean.setScore(TypeUtils.getJsonInteger(jsonObject2,"score"));
                    bean.setPkTimes(TypeUtils.getJsonInteger(jsonObject2,"pkTimes"));


                    ArrayList<CateWinRateBean> cateWinRates = new ArrayList<>();
                    JSONArray cateWinRateList = TypeUtils.getJsonArray(jsonObject2, "cateWinRates");
                    for (int j = 0; j < cateWinRateList.size(); j++) {
                        JSONObject cateWinRateJsonObject = cateWinRateList.getJSONObject(j);
                        CateWinRateBean cateWinRate = new CateWinRateBean();
                        cateWinRate.setId(cateWinRateJsonObject.getInt("id"));
                        cateWinRate.setName(cateWinRateJsonObject.getString("name"));
                        cateWinRate.setRate(TypeUtils.getJsonInteger(cateWinRateJsonObject,"rate"));
                        cateWinRate.setTimes(TypeUtils.getJsonInteger(cateWinRateJsonObject,"times"));

                        cateWinRates.add(cateWinRate);
                    }
                    bean.setCateWinRates(cateWinRates);

                    compareUserInfoBeanArrayList.add(bean);
                }

                new CompareDetailDialog(this.getActivity(),compareUserInfoBeanArrayList).builder().show();
            }
        } catch (Exception e) {
            ErrorUtils.outErrorLog(e);
        }


    }

    @UiThread
    @Override
    public void pkCompareError(String error) {
        Toast.makeText(this.getActivity(),error,Toast.LENGTH_SHORT).show();
    }

    public void compare(int playerId) {
        pkHallService.compare(playerId);
        //new CompareDetailDialog(this.getActivity()).builder().show();
    }

    public void openConfirmFragment(int roomId,int seatId) {
        getHomeActivity().openPKConfirmFragment(roomId,seatId,playerLimit,this);
    }
}
